<template>
  <el-dialog
    title="修改密码"
    :visible.sync="visibleDialog"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    width="30%"
  >
    <el-form ref="rowForm" :model="row" :rules="rules" label-width="100px">
      <el-form-item label="原密码" prop="passwordOld">
        <el-input v-model="row.passwordOld" type="password" autocomplete="off" show-password/>
      </el-form-item>
      <el-form-item label="新密码" prop="passwordNew">
        <el-input v-model="row.passwordNew" type="password" autocomplete="off" show-password/>
      </el-form-item>
      <el-form-item label="确认新密码" prop="passwordConfirm">
        <el-input v-model="row.passwordConfirm" type="password" autocomplete="off" show-password/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="btnSaveLoading" @click="handleSave">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import UserService from '@/api/UserService'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      btnSaveLoading: false,
      row: {
        passwordOld: null,
        passwordNew: null,
        passwordConfirm: null
      },
      rules: Object.freeze({
        passwordOld: [
          {required: true, message: '请输入原密码', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
        ],
        passwordNew: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
        ],
        passwordConfirm: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              }
              if (value === this.row.passwordNew) {
                callback()
              } else {
                callback(new Error('两次输入密码不一致'))
              }
            }, trigger: 'blur'
          }
        ]
      })
    }
  },
  computed: {
    visibleDialog: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    handleCancel() {
      this.$refs.rowForm.resetFields()
      this.visibleDialog = false
    },
    async handleSave() {
      const valid = await this.$refs.rowForm.validate()
      if (!valid) {
        return
      }
      this.btnSaveLoading = true
      const result = await UserService.changePassword(this.row.passwordOld, this.row.passwordNew).finally(() => (this.btnSaveLoading = false))
      result
        .ifToastMessage('密码修改成功', '密码修改失败')
        .ifSuccess(() => {
          this.handleCancel()
          this.$emit('ok')
        })
    }
  }
}
</script>
